
import datetime
import time
import openpyxl
from openpyxl.chart import LineChart, Reference
from initialization.redisInit import get_sync_redis
from monitor.adb_utils.adb_command import get_pid, get_memory, get_cpu, get_electric_quantity, get_flow, get_meminfo_total

def add_line_chart(title, y_title, x_title, wss, min_col, min_row, max_col, max_row):
    c1 = LineChart()
    c1.title = title  # 图的标题
    # c1.style = 12  # 线条的style
    c1.y_axis.title = y_title  # y坐标的标题
    c1.x_axis.title = x_title  # x坐标的标题
    y = Reference(wss, min_col=min_col, max_col = max_col, min_row=min_row, max_row=max_row)  # 图像的数据    起始行、起始列、终止行、终止列
    x = Reference(wss, min_col=1, min_row=2, max_row=max_row)   # X轴
    c1.add_data(y, titles_from_data=True)
    c1.set_categories(x)
    wss.add_chart(c1, "F1")  # 将图表添加到 sheet中

def write_in(package, duration):

    file = openpyxl.Workbook()  # 创建表格

    table = file.create_sheet('monitor', 0)
    table['A1'] = '时间'
    table['B1'] = '占用内存(%)'
    table['C1'] = 'CPU占用(%)'
    table['D1'] = '剩余电量(%)'
    table['E1'] = '使用流量(g)'

    pid = get_pid(package)

    row = 2

    start_time = datetime.datetime.now().timestamp()
    while True: # 持续测试

        if datetime.datetime.now().timestamp() > start_time + duration:
            get_sync_redis().delete(package)
            break

        now = time.strftime('%H:%M:%S', time.localtime())

        memory = get_memory(pid)
        table.cell(row, 1, value=now)
        table.cell(row, 2, value=round(float(int(memory)/int(get_meminfo_total()))*100, 2))

        cpu = None
        memory_ratio = None
        try:
            cpu = get_cpu(package)[0]
            memory_ratio = get_cpu(package)[1]
            table.cell(row, 3, value=float(cpu))
        except:
            row -= 1

        electric = get_electric_quantity()
        table.cell(row, 4, value=int(electric))

        flow = get_flow(pid)
        table.cell(row, 5, value=flow)

        try:
            file.save('./monitor/record/app内存&cpu&耗电量&流量测试.xlsx')
        except PermissionError:
            pass

        print(time.strftime('%H:%M:%S', time.localtime()), ' | ', memory, " | ", cpu, " | ", memory_ratio, " | ", electric, " | ", flow)

        row += 1
        time.sleep(1)

    wb = openpyxl.load_workbook("./monitor/record/app内存&cpu&耗电量&流量测试.xlsx")
    for i in range(0, 1):
        sheet = wb[wb.sheetnames[i]]
        add_line_chart(wb.sheetnames[i], "占用%", "时间", sheet, 2, 1, sheet.max_column, sheet.max_row)

    wb.save('./monitor/record/app内存&cpu&耗电量&流量测试.xlsx')

    # adb shell monkey -p tv.danmaku.bili --pct-motion 10 --pct-touch 90 --throttle 300 --ignore-crashes --ignore-timeouts --ignore-security-exceptions -v -v -v 1000 > log.txt













